package com.mingqi.enetconnected.primary.mytask.activity;


import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.github.chrisbanes.photoview.PhotoView;
import com.mingqi.enetconnected.R;
import com.mingqi.enetconnected.base.BaseActivity;
import com.mingqi.enetconnected.primary.mytask.adapter.EquityImgAdapter;
import com.mingqi.enetconnected.primary.mytask.adapter.EquityPageAdapter;
import com.mingqi.enetconnected.primary.mytask.event.EquityCheckEvent;
import com.mingqi.enetconnected.primary.mytask.event.RefuseReasonEvent;
import com.mingqi.enetconnected.util.resource.ResourceUtils;
import com.mingqi.enetconnected.view.Dialog.CommonDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class EquityCheckActivity extends BaseActivity {


    @BindView(R.id.tv_owner_name)
    TextView mTvOwnerName;
    @BindView(R.id.tv_id_card)
    TextView mTvIdCard;
    @BindView(R.id.tv_owner_phone)
    TextView mTvOwnerPhone;
    @BindView(R.id.rv_equity_img)
    RecyclerView mRvEquityImg;
    @BindView(R.id.ll_bottom)
    LinearLayout mllBottom;
    @BindView(R.id.tv_pass)
    TextView mTvPass;
    @BindView(R.id.tv_refuse)
    TextView mTvRefuse;
    EquityImgAdapter mEquityImgAdapter;
    private CommonDialog mCheckDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        EventBus.getDefault().register(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void hasRefuse(RefuseReasonEvent event){

        boolean refuse = event.isRefuse();
        if(refuse) {

            //并发送更新界面 不通过
            EventBus.getDefault().post(new EquityCheckEvent(false));
            finish();
        }
    }

    @Override
    protected int getLayoutID() {
        return R.layout.activity_equity_check;
    }

    @Override
    protected void initView() {

        setTitleName(ResourceUtils.getString(R.string.equity_data_check));
    }

    @Override
    protected void initData() {

        List<String> stringList = new ArrayList<>();
        for (int i = 0; i < 5; i++) {

            stringList.add("1");
        }
        mEquityImgAdapter = new EquityImgAdapter(stringList);
        mRvEquityImg.setAdapter(mEquityImgAdapter);
        mRvEquityImg.setLayoutManager(new LinearLayoutManager(mContext));

        mEquityImgAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

                showBigImg(view,position);
            }
        });

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
    }

    @Override
    protected void initClick() {

        mTvPass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(mCheckDialog == null) {

                    mCheckDialog = new CommonDialog(mContext, ResourceUtils.getString(R.string.confirm_pass_check));
                }
                mCheckDialog.show();

                mCheckDialog.setOnConfirmListener(new CommonDialog.OnConfirmListener() {
                    @Override
                    public void setOnConfirmClick(CommonDialog instance) {

                        instance.cancel();
                        Toast.makeText(EquityCheckActivity.this, "审核通过", Toast.LENGTH_SHORT).show();
                        EventBus.getDefault().post(new EquityCheckEvent(true));
                        finish();

                    }
                });
                mCheckDialog.setYesMessage(ResourceUtils.getString(R.string.confirm));
                mCheckDialog.setNoMsg(ResourceUtils.getString(R.string.cancel));
            }
        });

        mTvRefuse.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivity(RefuseReasonActivity.class);
            }
        });
    }

    private ViewPager vpEquityImg;
    //图片资源的数组
    private int[] imgEquityArray;
    //图片视图的集合
    private List<PhotoView> ivList;
    //放置圆点
    private LinearLayout llPoint;
    //实例化原点View
    private ImageView ivPoint;
    //点间距
    private int mPaintDistance;

    private void showBigImg(View view, int position) {

        int[] rvLocation = new int[2];
        mRvEquityImg.getLocationOnScreen(rvLocation);

        int width = mRvEquityImg.getWidth();
        int height = mRvEquityImg.getHeight();

        View equityImg = ResourceUtils.getLayoutView(R.layout.dialog_equity_img_show);

        vpEquityImg = equityImg.findViewById(R.id.vp_equity);
        ivPoint = equityImg.findViewById(R.id.iv_select);
        llPoint = equityImg.findViewById(R.id.ll_point);
        ImageView ivDismiss = equityImg.findViewById(R.id.iv_dismiss);

        //实例化图片资源
        imgEquityArray = new int[]{R.drawable.ic_dialog_success,R.drawable.welcome_bg,
                R.drawable.ic_dialog_success};

        ivList = new ArrayList<>();
        //获取一个Layout参数，设置为全屏
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);

        //循环创建View并加入到集合中
        for (int i = 0;i < imgEquityArray.length; i++){

            //new ImageView并设置全屏和图片资源
            PhotoView ivShow = new PhotoView(this);
            ivShow.setLayoutParams(params);
            Glide.with(mContext).load(imgEquityArray[i]).into(ivShow);
//            new PhotoViewAttacher(ivShow);
            //将ImageView加入到集合中
            ivList.add(ivShow);
        }
        //View集合初始化好后，设置Adapter
        vpEquityImg.setAdapter(new EquityPageAdapter(ivList));

        //循环新建底部圆点ImageView，将生成的ImageView保存到数组中
        for (int i = 0;i < imgEquityArray.length; i++){

            //一个小灰点是一个ImageView
            ImageView pointView = new ImageView(this);
            pointView.setBackgroundDrawable(getResources().getDrawable(R.drawable.point_img_normal));
            //初始化布局参数，父控件是谁，就初始化谁的布局参数
            LinearLayout.LayoutParams paramsPoint = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

            if (i > 0){

                //当添加的小圆点的个数超过一个的时候就设置当前小圆点的左边距为20dp;
                paramsPoint.leftMargin = 30;
            }
            //设置小灰点的宽高包裹内容
            pointView.setLayoutParams(paramsPoint);
            //将数组中的ImageView加入到ViewGroup
            llPoint.addView(pointView);
        }

        //监听布局是否已经完成  布局的位置是否已经确定
        ivPoint.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                //避免重复回调        出于兼容性考虑，使用了过时的方法
                ivPoint.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                //布局完成了就获取第一个小灰点和第二个之间left的距离
                mPaintDistance = llPoint.getChildAt(1).getLeft() - llPoint.getChildAt(0).getLeft();
            }
        });

        //设置滑动监听
        vpEquityImg.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                //当滑到第二个Pager的时候，positionOffset百分比会变成0，position会变成1，所以后面要加上position*mPaintDis
                int leftMargin = (int)(mPaintDistance * positionOffset) + position * mPaintDistance;
                //在父布局控件中设置他的leftMargin边距
                RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)ivPoint.getLayoutParams();
                params.leftMargin = leftMargin;
                ivPoint.setLayoutParams(params);
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        vpEquityImg.setCurrentItem(position);

        final PopupWindow mPopupWindow = new PopupWindow(view);
        mPopupWindow.setWidth(width);
        mPopupWindow.setHeight(height + mllBottom.getHeight());
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setContentView(equityImg);
        mPopupWindow.showAtLocation(mRvEquityImg, Gravity.LEFT | Gravity.TOP, 0, rvLocation[1]);

        ivDismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mPopupWindow.dismiss();
            }
        });
    }
}
